﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MementoClientConnectorInterfaces;
using System.Configuration;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.ComponentModel.Composition;

namespace MementoClientConnectorLibrary
{
    [Export(typeof(IMementoClientConnector))]
    public class TfsClientConnector : IMementoClientConnector
    {
        public List<TaskSourceSystemConfiguration> GetConfigurations()
        {
            return
                GetTfsClientConnectorSystems().Select(
                    x => new TaskSourceSystemConfiguration {UniqueID = x.UniqueID}).ToList();
        }

        public List<Task> GetTasksForUser(string configurationUniqueID, string userName)
        {
            var serverUrl = GetTfsClientConnectorSystems().First(f => f.UniqueID == configurationUniqueID).TfsServerUrl;
            var tfsServerUrl = new Uri(serverUrl);
            var tfsProjects = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsServerUrl);
            var workItemStore = new WorkItemStore(tfsProjects);
            
            var querySB = new StringBuilder();
            querySB.Append("Select ID, Title from WorkItems "); 
            querySB.AppendFormat("where [System.AssignedTo] = '{0}' ", userName);  
            querySB.Append("and [System.State] <> 'Removed'");

            var workItemCollection = workItemStore.Query(querySB.ToString());
            return workItemCollection.Cast<WorkItem>().Select(wi =>
                new Task
                {
                    ProjectID = wi.Project.Id.ToString(),
                    ProjectName = wi.Project.Name,
                    TaskName = wi.Title,
                    TaskID = wi.Id.ToString()
                }).ToList();     
        }

        private IEnumerable<TfsClientConnectorSystem> GetTfsClientConnectorSystems()
        {
            var tfsClientConnectorConfigSection = ConfigurationManager.GetSection("TfsClientConnector") as TfsClientConnectorConfigSection;
            if (tfsClientConnectorConfigSection == null)
            {
                return new List<TfsClientConnectorSystem>();
            }
            return tfsClientConnectorConfigSection.TfsSystems.OfType<TfsClientConnectorSystem>();
        }
    }
}
